<?php

namespace app\admin\model;

class Shoppingcart extends Base
{

    const STATUS_VALID = 1;  // 状态 - 有效
    const STATUS_DELETE = 2; // 状态 - 删除
    const STAUTS_LOWER_FRAME = 3; // 状态 - 下架


    // 数据表名称
    //protected $table;

    // 当前模型名称 不带前缀
    protected $name = 'shopping_cart';

    // 数据表主键 复合主键使用数组定义 不设置则自动获取
    protected $pk = 'id';


    /**
     * 获取当前用户购物车信息
     */
    public function getCurrentCartInfo($memberId){
        $where = [
            'a.status' => self::STATUS_VALID,
            'a.member_id' => $memberId
        ];
        $fields = 'a.product_id, a.count';
        $join = [
            ['__PRODUCT__ p', 'p.id = a.product_id']
        ];
        $order = 'a.create_date DESC';
        $cartList = self::alias('a')->where($where)->where(['p.status' => 1])->join($join)->field($fields)->order($order)->select();
        $cartTotal = self::alias('a')->where($where)->where(['p.status' => 1])->join($join)->count();
        $shoppingcartData = [
            'data' => $cartList ? $cartList : [],
            'total' => $cartTotal ? $cartTotal : 0
        ];

        return $shoppingcartData;
    }

    /**
     * 获取当前用户购物车内商品
     */
    public function getCurrentCartProduct($productId, $memberId){
        return self::where([
            'product_id' => $productId,
            'member_id' => $memberId,
        ])->find();
    }

    /**
     * 删除购物车内商品
     */
    /*public function delCartProduct($productId, $memberId){
        return self::where([
            'product_id' => $productId,
            'member_id' => $memberId,
            'status' => self::STATUS_DELETE
        ])->delete();
    }*/

    /**
     * 更新用户购物车
     */
    public function updateShoppingCart($data){
        if (isset($data['id']) && $data['id']) {
            // 更新
            return self::where(['id' => $data['id']])->update($data);
        } else {
            // 添加
            $data['id'] = get_uniqid_id();
            return self::save($data);
        }
    }

    /**
     * 购物车 - 删除单条
     */
    public function delShoppingCart($cartId, $memberId){
        return self::where([
            'id' => $cartId,
            'member_id' => $memberId,
        ])->delete();//->update(['status' => self::STATUS_DELETE]);
    }

    /**
     * 购物车 - 批量删除
     */
    public function delAllShoppingCarts($cartIds, $memberId){
        return self::where([
            'id' => ['in', $cartIds],
            'member_id' => $memberId,
        ])->delete();//->update(['status' => self::STATUS_DELETE]);
    }
}